<template>
  <div class="container">
    <div class="head-top">
      <span>{{symbol}}转账</span>
      <img
        @click="$router.push({name:'TransactionERC',params:{symbol:symbol,coin:coin}})"
        src="static/img/return.png"
      />
      <div class="read">{{parseFloat(accDiv(coin.balance,Math.pow(10,coin.decimals)))}}</div>
    </div>

    <div class="body">
      <div class="label">收款人钱包地址</div>
      <mt-field placeholder="收款人钱包地址" v-model="toAddress">
        <div @click="showContact" style="position: absolute;right:-.6rem;top:-.7rem">
          <img src="static/img/contact.png" style="width: 1.4rem;height: 1.4rem" />
        </div>
      </mt-field>
      <div class="label">转账金额 ({{coin.name}})</div>
      <mt-field :placeholder="'转账金额 ('+coin.name+')'" v-model="money"></mt-field>
      <div class="label">备注</div>
      <mt-field placeholder="备注" v-model="remark"></mt-field>
      <div class="label">矿工费用</div>
      <div class="range" v-if="switchType==false">
        <div>
          <div>矿工费用</div>
          <div>？</div>
        </div>
        <div>
          <mt-range
            v-model="rangeValue"
            :min="1"
            :max="60"
            :step="1"
            style="margin-top: 1rem;width: 90%;margin: 0px auto"
          ></mt-range>
        </div>
        <div class="btm-title">
          <span>慢</span>
          <div>{{displayValue}} ether</div>
          <span>快</span>
        </div>
      </div>

      <div class="high" v-if="switchType" style="position: relative">
        <div
          style="position: absolute;right:0;font-size:.8rem;color:#bfbfbf;z-index: 9999;top:.7rem;right:.2rem"
        >gwei</div>
        <mt-field placeholder="自定义Gas Price" v-model="myGasPrice"></mt-field>
        <mt-field placeholder="自定义Gas" v-model="myGasLimit"></mt-field>
        <mt-field
          placeholder="16进制数据"
          type="textarea"
          rows="4"
          v-model="hexData"
          style="margin-top:1rem;border:1px solid rgba(0,0,0,0.1);border-bottom:none"
        ></mt-field>
      </div>

      <div class="switch">
        <div>高级选项</div>
        <mt-switch style="transform: scale(.8);" v-model="switchType"></mt-switch>
      </div>

      <mt-button
        type="primary"
        style="background: #36BAC9;display: block;width: 100%;margin-top:2rem"
        @click="togglePopup"
      >下一步</mt-button>

      <mt-popup
        id="enterPopul"
        v-model="popupVisible"
        position="bottom"
        style="width: 100%;padding: 0rem 0rem 1rem 0rem"
      >
        <h3 style="margin:.5rem 0rem;text-align: center">支付详情</h3>
        <div class="label">订单信息</div>
        <mt-field
          label="订单信息"
          value="转账"
          readonly
          style="width: 90%;margin: 0px auto;border-top: 1px solid rgba(0,0,0,0.1)"
        ></mt-field>
        <div class="label">收款地址</div>
        <mt-field label="收款地址" readonly v-model="toAddress" style="width: 90%;margin: 0px auto"></mt-field>
        <div class="label">付款钱包</div>
        <mt-field label="付款钱包" readonly v-model="fromAddress" style="width: 90%;margin: 0px auto"></mt-field>
        <div class="label">矿工费</div>
        <mt-field
          label="矿工费"
          readonly
          :value="poundage+' ETH ≈ '+(poundage*currentAccount.ethPrice*global.rate).toFixed(4) +' CNY'"
          style="width: 90%;margin: 0px auto"
        ></mt-field>
        <div class="label">金额</div>
        <mt-field
          label="金额"
          readonly
          :value="money+' '+coin.name"
          style="width: 90%;margin: 0px auto"
        ></mt-field>

        <mt-button
          type="primary"
          style="background: #36BAC9;display: block;width: 90%;margin: 0px auto;margin-top:1rem"
          @click="enterPwd"
        >确认</mt-button>
      </mt-popup>

      <mt-popup
        id="enterPopulPwd"
        v-model="popupVisiblePwd"
        position="bottom"
        style="width: 100%;padding: 0rem 0rem 40% 0rem"
      >
        <h3 style="margin:.5rem 0rem;text-align: center">确认交易</h3>

        <mt-field
          label="密码"
          placeholder="请输入密码"
          type="password"
          v-model="pwd"
          style="width: 90%;margin: 0px auto"
        ></mt-field>
        <mt-button
          type="primary"
          style="background: #36BAC9;display: block;width: 90%;margin: 0px auto;margin-top:1rem"
          @click="reEnterPwd"
        >确认</mt-button>
      </mt-popup>
    </div>

    <mt-popup
      v-model="showcontact"
      popup-transition="popup-fade"
      style="width: 80%;padding:.5rem;border-radius:.3rem;overflow: hidden;"
    >
      <div
        style=" position: absolute;right:1rem;top:.1rem;font-size: 1.7rem;color:gray"
        @click="showcontact=false"
      >×</div>

      <div style="margin-bottom: .1rem;text-align: center">
        <!--<img src="static/img/contact.png" style="width: 1.8rem;height: 1.8rem;display: inline-block;margin-top: .3rem">-->
        <!---->
        <div
          style="font-size: 1.2rem;font-weight: 600;padding-bottom: 0.5rem; border-bottom: 0.5px solid rgba(0,0,0,0.1)"
        >联系人</div>
      </div>

      <div
        v-if="!contactList||contactList.length<1"
        style="position:absolute; left:40%;top:40%"
      >无联系人~</div>

      <div style="width: 100%;max-height:25rem;min-height: 8rem; overflow-x:hidden;">
        <div class="contactBox">
          <div v-for="contact,index in contactList" @click="choiceContact(contact)">
            <div>
              <img src="static/img/contact.png" />
            </div>
            <div>
              <div>{{contact.name}}</div>
              <div>{{contact.address}}</div>
            </div>
            <div>{{contact.date}}</div>
          </div>
        </div>
      </div>
    </mt-popup>
  </div>
</template>


<script>
import BigNumber from "bignumber.js";
import web3Utils from "../../service/eth/web3Utils";
import accountUtils from "../../service/eth/accountUtils";
import { mapGetters, mapActions } from "vuex";
import { Range, Switch, Button, Popup } from "mint-ui";
import { Toast, Dialog } from "vant";

export default {
  components: {},
  data() {
    return {
      symbol: "",
      coin: "",
      showcontact: false,
      popupVisible: false,
      popupVisiblePwd: false,
      switchType: false,
      rangeValue: 1,
      displayValue: 0.00006,
      fromAddress: "",
      toAddress: "",
      money: "",
      remark: "",
      gasLimit: 100000,
      gasPrice: 1000000000,
      myGasLimit: "",
      myGasPrice: "",
      poundage: 0,
      data: "",
      hexData: "",
      pwd: "",
    };
  },
  computed: {
    ...mapGetters([
      "currentAccount",
      "wallet",
      "accountIndex",
      "contactList",
      "messageList",
    ]),
  },
  created() {
    this.symbol = this.currentAccount.currentCoin.name;
    this.coin = this.currentAccount.currentCoin;

    this.fromAddress = this.currentAccount.address;
    this.poundage = (this.rangeValue * this.gasLimit) / 1000000000;
  },
  methods: {
    ...mapActions(["setWalletAccountByIndex", "setMessageList"]),
    accMul(arg1, arg2) {
      return this.convertBigNumber(
        new BigNumber(arg1).multipliedBy(arg2).valueOf()
      );
    },
    accDiv(arg1, arg2) {
      return this.convertBigNumber(
        new BigNumber(arg1).dividedBy(arg2).valueOf()
      );
    },
    convertBigNumber: (param) => {
      let strParam = String(param);
      let flag = /e/.test(strParam);
      if (!flag) return param;

      // 指数符号 true: 正，false: 负
      let sysbol = true;
      if (/e-/.test(strParam)) {
        sysbol = false;
      }
      // 指数
      let index = Number(strParam.match(/\d+$/)[0]);
      // 基数
      let basis = strParam.match(/^[\d\.]+/)[0].replace(/\./, "");

      if (sysbol) {
        return basis.padEnd(index + 1, 0);
      } else {
        return basis.padStart(index + basis.length, 0).replace(/^0/, "0.");
      }
    },
    togglePopup() {
      let _this = this;
      if (!this.toAddress) {
        Dialog.alert({
          title: "提示",
          message: "请填写收款地址",
        }).then(() => {});
        return;
      } else if (!this.global.web3.utils.isAddress(this.toAddress)) {
        Dialog.alert({
          title: "提示",
          message: "不是有效的收款地址",
        }).then(() => {});
        return;
      } else if (!this.money) {
        Dialog.alert({
          title: "提示",
          message: "请填写转账金额",
        }).then(() => {});
        return;
      }
      if (!parseFloat(this.money)) {
        Dialog.alert({
          title: "提示",
          message: "请输入正确的数字",
        }).then(() => {});
        return;
      } else if (
        this.coin.name == "DFP" &&
        parseFloat(
          _this.accMul(this.money, Math.pow(10, this.coin.decimals))
        ) == parseFloat(this.coin.balance)
      ) {
        Dialog.alert({
          title: "提示",
          message:
            "DFP无法全部转出，请在您的钱包内留一个最小余额，比如0.00000001",
        }).then(() => {
          // on close
        });

        return;
      } else if (
        parseFloat(_this.accMul(this.money, Math.pow(10, this.coin.decimals))) >
        parseFloat(this.coin.balance)
      ) {
        Dialog.alert({
          title: "提示",
          message: "您的余额不足",
        }).then(() => {});
        return;
      }
      if (!this.switchType) {
        if (this.poundage > this.currentAccount.ethBalance) {
          Dialog.alert({
            title: "提示",
            message: "您的余额不足以支付手续费",
          }).then(() => {});
          return;
        }
      } else {
        if (this.switchType) {
          if (!this.myGasPrice) {
            Dialog.alert({
              title: "提示",
              message: "请输入Gas Price",
            }).then(() => {});
            return;
          } else if (
            parseInt(this.myGasPrice % 1) != 0 ||
            parseInt(this.myGasPrice) < 1
          ) {
            Dialog.alert({
              title: "提示",
              message: "Gas Price必须为大于0的整数",
            }).then(() => {});
            return;
          } else if (!this.myGasLimit) {
            Dialog.alert({
              title: "提示",
              message: "Gas Limit必须为整数",
            }).then(() => {});
            return;
          } else if (parseInt(this.myGasLimit % 1) != 0) {
            Dialog.alert({
              title: "提示",
              message: "Gas Limit必须为整数",
            }).then(() => {});
            return;
          } else if (this.myGasLimit < 60000) {
            Dialog.alert({
              title: "提示",
              message: "Gas Limit不能小于60000",
            }).then(() => {});
            return;
          } else if (
            (this.myGasPrice / 1000000000) * this.myGasLimit >
            this.currentAccount.ethBalance
          ) {
            Dialog.alert({
              title: "提示",
              message: "您的余额不足以支付手续费",
            }).then(() => {});
            return;
          }
          if (this.hexData != "") {
            if (
              !this.global.web3.utils.isHex(
                this.hexData.substring(0, 2) != "0x" ||
                  this.hexData.substring(2, this.hexData.length)
              )
            ) {
              Dialog.alert({
                title: "提示",
                message: "无效的16进制数据",
              }).then(() => {});
              return;
            }
          }
        }
      }

      this.popupVisible = !this.popupVisible;
    },
    enterPwd() {
      this.popupVisible = !this.popupVisible;
      this.popupVisiblePwd = !this.popupVisiblePwd;
    },
    reEnterPwd() {
      let _this = this;
      if (!this.pwd) {
        this.popupVisiblePwd = false;
        Dialog.alert({
          title: "提示",
          message: "请输入密码!",
        }).then(() => {});
        return;
      } else if (this.pwd != this.currentAccount.password) {
        this.popupVisiblePwd = false;
        Dialog.alert({
          title: "提示",
          message: "密码错误!",
        }).then(() => {});
        return;
      }

      this.popupVisiblePwd = !this.popupVisiblePwd;
      Toast.loading({
        duration: 0,
        forbidClick: true,
        message: "发送中",
      });

      let nonce = _this.currentAccount.nonce;
      for (
        let i = 0;
        i < _this.currentAccount.coins[this.coin.name].length;
        i++
      ) {
        if (_this.currentAccount.coins[this.coin.name].pending == true) {
          nonce += 1;
          _this.currentAccount.nonce = nonce;
        }
      }
      _this.setWalletAccountByIndex(_this.currentAccount, _this.accountIndex);

      let abi = _this.coin.abi;
      let address = _this.coin.address;

      let isAddSend = false;
      let isAddget = false;
      let tran = {};

      web3Utils
        .getCoinContract(_this.global.web3, abi, address)
        .then((contract) => {
          contract.methods
            .transfer(
              _this.toAddress,
              _this.convertBigNumber(
                _this
                  .accMul(_this.money, Math.pow(10, _this.coin.decimals))
                  .valueOf()
              ) + ""
            )
            .send({
              from: _this.currentAccount.address,
              gas: _this.coin.name == "BCF" ? 120000 : _this.gasLimit,
              gasPrice: _this.gasPrice,
              data: !_this.switchType
                ? _this.global.web3.utils.toHex(_this.remark)
                : _this.hexData,
            })
            .on("transactionHash", function (hash) {
              console.log("交易hash:" + hash);

              tran = {
                name: _this.symbol,
                fromAddress: _this.currentAccount.address,
                toAddress: _this.toAddress,
                img: "static/img/to2.png",
                error: false,
                get: false,
                txhash: hash,
                blockNumber: "",
                blockHash: "",
                date: "",
                timeStamp: (new Date().getTime() + "").substring(0, 10),
                value: _this.accMul(
                  _this.money,
                  Math.pow(10, _this.coin.decimals)
                ),
                decimals: _this.coin.decimals,
                input: !_this.switchType
                  ? _this.global.web3.utils.toHex(_this.remark)
                  : _this.hexData,
                pending: true,
              };
              console.log(tran);

              _this.currentAccount.coins[_this.coin.name].push(tran);
              _this.currentAccount.nonce = _this.currentAccount.nonce + 1;
              _this.setWalletAccountByIndex(
                this.currentAccount,
                _this.accountIndex
              );

              Toast.clear();
              setTimeout(() => {
                _this.$router.replace({
                  name: "TransactionERC",
                  params: { symbol: _this.symbol, coin: _this.coin },
                });
              }, 200);
            })
            .on("receipt", function (receipt) {
              console.log(receipt);
              tran.gasMoney = _this.global.web3.utils.fromWei(
                parseInt(receipt.gasUsed) * 1000000000 + "",
                "ether"
              );
              tran.blockNumber = receipt.blockNumber;
              tran.blockHash = receipt.blockHash;

              _this.currentAccount.currentCoin -=
                _this.money * Math.pow(10, _this.coin.decimals);

              if (!isAddSend) {
                isAddSend = true;

                let message = {
                  name: "ether",
                  message:
                    "转账通知: " +
                    _this.money +
                    " " +
                    _this.symbol +
                    " " +
                    "转账成功",
                  type: "to",
                  from: _this.currentAccount.address,
                  to: _this.toAddress,
                  timeStamp: new Date().getTime(),
                  isRead: false,
                  tran: tran,
                };
                _this.messageList.push(message);
                _this.setMessageList(messageList);
              }
              if (!isAddget) {
                isAddget = true;

                let message = {
                  name: "ether",
                  message:
                    "收款通知: " +
                    _this.money +
                    " " +
                    _this.symbol +
                    " " +
                    "收款成功",
                  type: "get",
                  from: _this.currentAccount.address,
                  to: _this.toAddress,
                  timeStamp: new Date().getTime(),
                  isRead: false,
                  tran: tran,
                };
                _this.messageList.push(message);
                _this.setMessageList(messageList);
              }

              Toast.clear();
            })
            .on("confirmation", function (confirmationNumber, receipt) {
              console.log(confirmationNumber);
            })
            .on("error", (error) => {});
        });
    },
    getGasPrice() {
      let _this = this;
      _this.global.web3.eth.getGasPrice().then((price) => {
        _this.gasPrice = (price * 1.2).toFixed();
        _this.rangeValue = parseInt((price * 1.2) / 1000000000);
      });
    },
    getNonce() {
      let _this = this;
      _this.global.web3.eth
        .getTransactionCount(_this.currentAccount.address)
        .then((nonce) => {
          _this.currentAccount.nonce = nonce;
          _this.setWalletAccountByIndex(
            this.currentAccount,
            _this.accountIndex
          );
        });
    },
    showContact() {
      this.showcontact = true;
    },
    choiceContact(contact) {
      this.toAddress = contact.address;
      this.showcontact = false;
    },
    toNonExponential(num) {
      var m = num.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/);
      return num.toFixed(Math.max(0, (m[1] || "").length - m[2]));
    },
  },
  async mounted() {
    let _this = this;

    if (_this.global.web3 == "") {
      let fdStart = _this.currentAccount.priKey.indexOf("0x");
      if (fdStart != -1) {
        _this.currentAccount.priKey = _this.currentAccount.priKey.substring(
          2,
          _this.currentAccount.priKey.length
        );
      }

      accountUtils
        .initProviderFromPrivateKey(
          _this.currentAccount.priKey,
          _this.global.infuraAK
        )
        .then((provide) => {
          accountUtils
            .initWeb3FromProvider(provide)
            .then(({ web3, provider, priKey, pubKey, address }) => {
              _this.global.setWeb3(web3);
              _this.getGasPrice();
              _this.getNonce();
            });
        });
    } else {
      this.getGasPrice();
      this.getNonce();
    }
  },
  watch: {
    rangeValue(newvalue, oldvalue) {
      this.displayValue = (this.rangeValue * this.gasLimit) / 1000000000;
      this.poundage = (this.rangeValue * this.gasLimit) / 1000000000;
    },
    myGasPrice(newvalue, oldvalue) {
      this.poundage = this.myGasPrice * this.myGasLimit;
    },
    myGasLimit(newvalue, oldvalue) {
      this.poundage = (this.myGasPrice * this.myGasLimit) / 1000000000;
    },
    switchType(newvalue, oldvalue) {
      if (this.switchType) {
        this.poundage = (this.myGasPrice * this.myGasLimit) / 1000000000;
      } else {
        this.displayValue = (this.rangeValue * this.gasLimit) / 1000000000;
        this.poundage = (this.rangeValue * this.gasLimit) / 1000000000;
      }
    },
    popupVisiblePwd(newvalue, oldvalue) {
      if (this.popupVisiblePwd) {
        this.pwd = "";
      }
    },
  },
};
</script>
<style lang="less" scoped>
@import url("../../assets/css/transactionTo.less");
</style>

